//  我的-录取查询页面
const baseUrl = 'https://gsdse.cn/api/KJRecruit';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    personInfo: {
      userId: '10086',
      realname: "",
      Email: "",
      phoneNumber: "",
      passStatus: 0,
      /* 用户被录取状态,用数字表示.其中:
          0 -> 未被选中
          1 -> 第一志愿录取
          2 -> 第二志愿录取
          3 -> 两个志愿都被录取 
          4 -> 查询无结果--->后端出现错误
          5 -> 至少还有一个部门还在审核
      */
      departmentId: ''
    },
    inquiryWay: "Email",
    openid: "#",
  },

  //---------------------------------------------------------------------------------------
  //methods-------------------------------------------------------------------

  //输入并更新data域
  write: function (options) {
    //获取输入框输入的内容
    // console.log(options)
    let id = options.currentTarget.id
    let value = options.detail.value
    // console.log(id + ":" + value)
    this.setData({
      ['personInfo.' + id]: value
    })
  },

  //-------------------------------------------------------------------------
  //查询方式转换
  async turnDianhua() {
    var that = this
    const isWolf = await getApp().showWolf()
    if (isWolf) {
      that.setData({
        inquiryWay: "pho",
      })
    } else {
      wx.showToast({
        title: '很抱歉，本功能暂不开放',
        icon: "none"
      })
    }
  },

  turnYouxiang() {
    this.setData({
      inquiryWay: "Email",
    })
  },
  //----------------------------------------------------------------
  // 查询
  async getData() {
    //判断姓名的长度
    if (this.data.personInfo.realname.length == 0) {
      wx.showToast({
        title: '姓名不能为空',
        icon: 'error'
      })
    }
    //判断手机号的长度
    else if (this.data.inquiryWay == "手机号" && this.data.personInfo.phoneNumber.length != 11) {
      console.log(this.data.personInfo.phoneNumber.length)
      wx.showToast({
        title: '手机号码有误',
        icon: 'error'
      })
    }
    //判断邮箱的长度
    else if (this.data.inquiryWay == "Email" && this.data.personInfo.Email.length == 0) {
      wx.showToast({
        title: '邮箱不能为空',
        icon: 'error'
      })
    }
    //开始查询
    else {
      wx.showLoading({
        title: '查询中',
        mask: true,
      })
      //防止代码一出问题就卡住
      setTimeout(function () {
        wx.hideLoading()
      }, 3000)
      //查询用户ID
      console.log(this.data.personInfo.realname, this.data.personInfo.phoneNumber, this.data.personInfo.Email)
      const userId = await this.selectUserId(this.data.personInfo.realname, this.data.personInfo.phoneNumber, this.data.personInfo.Email)
      this.setData({
        ['personInfo.userId']: userId
      })
      //存储用户信息
      const userInfo = await this.stroageUserInfo(userId)
      //查询用户录取情况
      const passStatus = await this.selectUserAdmission(userId)
      this.setData({
        ['personInfo.passStatus']: passStatus
      })
      if (passStatus === 1 || passStatus === 2) {
        //获取志愿信息
        const willing = await this.selectUserWilling(this.data.personInfo.passStatus)
        //通过录取信息更改所属部门
        await this.updateUser(this.data.personInfo.userId, willing, userInfo)
      }
      //跳转页面
      this.navTo()
    }
  },

  //通过电话或邮箱查询用户ID
  selectUserId(name, phoneNumber, email) {
    return new Promise((resolve, reject) => {
      //电话查询
      var that = this
      if (this.data.inquiryWay == "pho") {
        //通过姓名和手机号获取到用户ID
        wx.request({
          url: baseUrl + '/selectUserByRealNameAndPhone',
          method: 'POST',
          data: {
            userName: name,
            phoneNumber: phoneNumber,
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            console.log(res)
            resolve(res.data.data.userId)
          },
        })
      } else { //邮箱查询
        //通过姓名和邮箱查询用户ID
        wx.request({
          url: baseUrl + '/selectUserByRealNameAndEmail',
          method: 'POST',
          data: {
            userName: name,
            email: email,
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            // console.log(res)
            if (res.data.data.userId) {
              resolve(res.data.data.userId)
            }
          }
        })
      }
    })
  },

  //查询用户被哪个部门录取
  selectUserAdmission(userId) {
    // console.log(userId)
    return new Promise((resolve, reject) => {
      var that = this
      wx.request({
        url: baseUrl + '/selectUserByLastPass',
        method: 'POST',
        data: {
          // UserId: that.data.personInfo.userid,
          UserId: userId,
          // UserId:'2'
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          // console.log(res.data)

          if (res.data.msg === '抱歉，都没有被选中') {
            console.log('抱歉，都没有被选中')
            resolve(0)
          } else if (res.data.msg === '恭喜你第一志愿通过') {
            console.log('恭喜你第一志愿通过')
            resolve(1)
          } else if (res.data.msg === '恭喜你第二志愿通过') {
            console.log('恭喜你第二志愿通过')
            resolve(2)
          } else if (res.data.msg === '恭喜你被两个部门选中') {
            console.log('恭喜你被两个部门选中')
            resolve(3)
          } else if (res.data.msg === '部门还在审核，给您带来不便了！') {
            console.log(res.data.msg)
            resolve(5)
          } else {
            console.log('草又接收不到录取信息了')
            resolve(4)
          }
        }
      })
    })
  },

  //获取志愿信息 
  selectUserWilling(passStatus) {
    return new Promise((resolve, reject) => {
      var that = this
      wx.request({
        url: baseUrl + '/SelectUserWilling',
        method: 'POST',
        data: {
          userId: that.data.personInfo.userId
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          if (passStatus === 1) {
            resolve(res.data.data.firstWilling)
          } else if (passStatus === 2) {
            resolve(res.data.data.secondWilling)
          }
        }
      })
    })
  },

  //通过录取信息跳转到对应页面
  navTo() {
    if (this.data.personInfo.passStatus === 4 || this.data.personInfo.passStatus === 0 || this.data.personInfo.passStatus === 5) {
      // wx.hideLoading()
      wx.navigateTo({
        url: '../admissionResult/admissionResult?userId=' + this.data.personInfo.userId + '&&passStatus=' + this.data.personInfo.passStatus,
      })
    } else if (this.data.personInfo.passStatus === 3) {
      wx.navigateTo({
        url: '../invertSelection/invertSelection?userId=' + this.data.personInfo.userId
      })
    } else if (this.data.personInfo.passStatus === 1 || this.data.personInfo.passStatus === 2) {
      wx.navigateTo({
        url: '../admissionResult/admissionResult?userId=' + this.data.personInfo.userId + '&&passStatus=' + this.data.personInfo.passStatus,
      })
    }
  },

  //志愿录取之后，修改用户的departmentId值
  updateUser(userId, departmentId, userInfo) {
    console.log(userInfo)
    console.log(departmentId)
    var that = this
    that.updateDepartmentId({
      userId: userId,
      applyId: userInfo.applyId,
      phoneNumber: userInfo.phoneNumber,
      email: userInfo.email,
      positionName: 0,
      position: '干事',
      departmentId: departmentId,
      userName: userInfo.userName,
      schoolClass: userInfo.schoolClass,
      wxuserId: userInfo.wxuserId,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl
    });
  },
  updateDepartmentId(userInfo){
    const that=this
    if(userInfo.userId==null){
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '获取用户信息失败，请刷新小程序缓存，注意不是重新进入小程序！若仍然无效，请联系管理员。',
        cancelColor: 'cancelColor',
      })
      return false
    }
    console.log(userInfo)
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + '/updateUser',
        method: 'POST',
        header: {
          "Content-Type": "application/json"
        },
        data: {
          userId: userInfo.userId,
          applyId: userInfo.applyId,
          userName: userInfo.userName,
          phoneNumber: userInfo.phoneNumber,
          email: userInfo.email,
          positionName: userInfo.positionName,
          position: userInfo.position,
          departmentId: userInfo.departmentId,
          schoolClass: userInfo.schoolClass,
          wxuserId: userInfo.wxuserId,
          avatarUrl: userInfo.avatarUrl,
          nickName: userInfo.nickName
        },
        success: function (res) {
          if(res.data.code===0){
            console.log("修改成功", res.data)
            resolve(true)
          }
          else{
            wx.showModal({
              showCancel: false,
              title: '提示',
              content: '获取用户信息失败，请刷新小程序缓存，注意不是重新进入小程序！若仍然无效，请联系管理员。',
              cancelColor: 'cancelColor',
            })
            resolve(false)
          }
        },
        fail: function (err) {
          that.showError('修改失败')
          console.error(err)
          reject(false)
        }
      })
    })
  },

  //通过departmentName反推departmentId
  getDepartmentId(departmentName) {
    var departmentArray = ["无", '秘书处', '网络研发部', "影视部", '动画部', "PC技术部", "新媒体运营部", 'UI设计部']
    for (let i = 1; i <= departmentArray.length; i++) {
      if (departmentName === departmentArray[i]) {
        return i
      }
    }
  },

  //存储用户信息
  stroageUserInfo(userId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + '/selectUser',
        method: 'POST',
        data: {
          userId: userId
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res.data.data)
          resolve(res.data.data)
        }
      })
    })
  },

  //-----------------------------------------------------------------
  //测试用函数
  testNav1() {
    //跳转到选部门界面
    wx.navigateTo({
      url: '../invertSelection/invertSelection?userId=' + 5
    })
  },

  testNav2() {
    //跳转到录取结果界面
    wx.navigateTo({
      url: '../admissionResult/admissionResult?id=' + encodeURIComponent(this.data.openid),
    })
  },

  //----------------------------------------------------------------
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    // const userId = await this.selectUser();
    //*****
    wx.request({
      url: baseUrl + '/returnFalse',
      success: function (res) {
        console.log(res.data)
        that.setData({
          openid: options.openid
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    //检测是否完善个人资料
    const userInfo = await getApp().selectUser()
    const isInfoEdited = await getApp().IsPersonalInfoEdit(userInfo)
    if (!isInfoEdited) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请先完善个人资料，以便您后续可以查询录取情况；如果本提示在编辑完资料后仍然出现，请尝试等待片刻并刷新小程序。',
        cancelColor: 'cancelColor',
        success: res => {
          if (res.confirm) {
            //点了确定
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})